﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

/// <summary>
/// 可拖拽LayoutGroup
/// </summary>
public abstract class DragLayoutGroupBase: MonoBehaviour
{
    public virtual event Action<RectTransform> OnLayoutSiblingChange;
    public RectTransform casheDragParent;
    //public RectTransform dragTraget;

    public HorizontalOrVerticalLayoutGroup childGroup;
    public RectTransform childGroupRectTransform;
    /// <summary>
    /// 是否可激活拖拽
    /// </summary>
    virtual public bool DragEnabled
    {
        get
        {
            return childGroupRectTransform.GetChild(0).GetComponent<CanvasGroup>().interactable;
        }
        set
        {
            for (int i = 0; i < childGroupRectTransform.childCount; i++)
            {
                CanvasGroup canvasGroup = childGroupRectTransform.GetChild(i).GetComponent<CanvasGroup>();
                canvasGroup.interactable = value;
                canvasGroup.blocksRaycasts = value;
                canvasGroup.alpha = (value == true ? 1 : 0.8f);
            }
        }
    }
    protected virtual void Reset()
    {
        casheDragParent = this.GetComponent<RectTransform>();
        childGroupRectTransform = this.GetComponent<RectTransform>();
    }

    /// <summary>
    /// 设置拖拽对象的层级顺序
    /// </summary>
    /// <param name="target"></param>
    public virtual void SetDragSiblingIndex(Transform target)
    {
        if (childGroup is VerticalLayoutGroup)
        {
            //posIndex = (int)target.anchoredPosition.y;
            for (int i = 0; i < childGroupRectTransform.childCount; i++)
            {
                if (target.position.y >= childGroupRectTransform.GetChild(i).position.y)
                {
                    target.SetSiblingIndex(i);
                    break;
                }
            }
        }
        else if (childGroup is HorizontalLayoutGroup)
        {
            //posIndex = (int)target.anchoredPosition.x;
            for (int i = 0; i < childGroupRectTransform.childCount; i++)
            {
                if (target.position.x >= childGroupRectTransform.GetChild(i).position.x)
                {
                    target.SetSiblingIndex(i);
                    break;
                }
            }
        }
        OnLayoutSiblingChange?.Invoke(childGroupRectTransform);
    }

}

